#!/usr/bin/env python
# coding: utf-8
# @Time    : 2021/11/4 17:15
# @Author  : YD
# @Email   : dinhe_1985@126.com 
# @File    : zbx_api.py
# @Software: PyCharm
# @Blog    : www.noteshare.cn

"""
通过Zabbix API实现Zabbix的自动管理
"""
from pyzabbix import ZabbixAPI, ZabbixAPIException
from lib.zbx_log import LoggingRecord

logger = LoggingRecord('file_console_logger', 'info')


class AutoZabbix:
    """
    通过Zabbix API实现相关功能自动化
    主机
    用户
    操作
    """

    def __init__(self, zabbixserver, zabbixuser, zabbixpassword):
        self.server = zabbixserver
        self.user = zabbixuser
        self.password = zabbixpassword

    def _login(self):
        """
        登录zabbix 返回token
        """
        zabbix_api = ZabbixAPI(self.server)
        zabbix_api.login(self.user, self.password)
        return zabbix_api

    def add_webmonitor(self, *args, **kwargs):
        """
        获取所有用户
        """
        with self._login() as zabbix_api:
            response = zabbix_api.httptest.create(*args, **kwargs)
            return response

    def add_trigger(self, *args, **kwargs):
        """
        获取所有用户
        """
        with self._login() as zabbix_api:
            response = zabbix_api.trigger.create(*args, **kwargs)
            return response

    ################################ User/Usergroup Function ##################################
    def get_all_user_group_id(self):
        '''
        获取所有用户组ID
        '''
        with self._login() as zabbix_api:
            response = zabbix_api.usergroup.get(output_='usrgrpid')
            result = []
            for i in range(0, len(response)):
                result.append(response[i]['usrgrpid'])
            return result

    def user_group_exists(self, usergroup):
        '''
        判断用户组是否存在
        '''
        with self._login() as zabbix_api:
            response = zabbix_api.usergroup.get(filter={'name': usergroup})
            if len(response) > 0:
                return True
            else:
                return False

    def user_exists(self, user):
        '''
        判断用户组是否存在
        '''
        with self._login() as zabbix_api:
            response = zabbix_api.user.get(filter={'alias': user})
            if len(response) > 0:
                return True
            else:
                return False

    def get_group_userlist(self, usrgrpid):
        '''
        获取用户组中的用户
        '''
        with self._login() as zabbix_api:
            response = zabbix_api.usergroup.get(selectUsers="userid", filter={"usrgrpid": usrgrpid})
            result = []
            for i in response[0]['users']:
                result.append(i['userid'])
            return result

    def get_user_grouplist(self, userid):
        '''
        获取用户所在用户组
        '''
        with self._login() as zabbix_api:
            response = zabbix_api.user.get(selectUsrgrps="usrgrpid", filter={"userid": userid})
            result = []
            for i in response[0]['usrgrps']:
                result.append(i['usrgrpid'])
            return result

    def id_to_usergroupname(self, groupid):
        '''
        根据id获取用户组名称
        '''
        with self._login() as zabbix_api:
            response = zabbix_api.usergroup.get(filter={"usrgrpid": groupid, "output": "extend"})
            return response[0]['name']

    def id_to_username(self, userid):
        '''
        根据id获取用户名称
        '''
        with self._login() as zabbix_api:
            response = zabbix_api.user.get(filter={"userid": userid, "output": "extend"})
            return response[0]['alias']

    def get_usrgrpid(self, usrgrpname):
        '''
        获取用户组ID
        :param usrgrpname:
        :return:
        '''
        with self._login() as zabbix_api:
            response = zabbix_api.usergroup.get(filter={"name": usrgrpname, "output": "usrgrpid"})
            return response[0]['usrgrpid']

    def get_usrid(self, username):
        '''
        获取用户ID
        :param username:
        :return:
        '''
        with self._login() as zabbix_api:
            response = zabbix_api.user.get(filter={"alias": username, "output": "userid"})
            return response[0]['userid']

    def create_usergroup(self, usergroupname, hostgroupid, permission="2"):
        '''
        创建用户组
        '''
        with self._login() as zabbix_api:
            response = zabbix_api.usergroup.create(name=usergroupname,
                                                   rights={"permission": permission, "id": hostgroupid})
            return response["usrgrpids"][0]

    def create_user(self, alias, passwd, usergroupid, user_media):
        '''
        创建用户
        :param alias: 
        :param passwd: 
        :param usergroupid: 
        :param user_medias: 
        :return: 
        '''

        usrgrps = []
        user_medias = []
        for i in usergroupid:
            usrgrps.append({"usrgrpid": "{}".format(i)})
        for i in user_media:
            user_medias.append(i)

        user_medias_parameter = {
            "mediatypeid": "101",
            "sendto": [
                "{}".format(user_medias)
            ],
            "active": 0,
            "severity": 63,
            "period": "1-7,00:00-24:00"
        }

        with self._login() as zabbix_api:
            response = zabbix_api.user.create(alias=alias, passwd=passwd, usrgrps=usrgrps,
                                              user_medias=user_medias_parameter)
            return response

    ################################ User/Usergroup Function ##################################

    ################################ Host/Hostgroup Function ##################################
    def host_exists(self, host_name):
        '''
        判断主机是否存在
        '''
        with self._login() as zabbix_api:
            response = zabbix_api.host.get(filter={'host': host_name})
            if response:
                return True
            else:
                return False

    def host_group_exists(self, host_group_name):
        '''
        判断主机组是否存在
        '''
        with self._login() as zabbix_api:
            response = zabbix_api.hostgroup.get(filter={'name': host_group_name})
            if response:
                return True
            else:
                return False

    def get_group_hostlist(self, groupid):
        '''
        获取主机组组中的用户
        '''
        with self._login() as zabbix_api:
            response = zabbix_api.hostgroup.get(selectHosts="host", filter={"name": groupid})
            result = []
            for i in response[0]['hosts']:
                result.append(i['hostid'])
                return result

    def get_host_grouplist(self, hostid):
        '''
        获取主机所在用户组
        '''
        with self._login() as zabbix_api:
            response = zabbix_api.host.get(selectGroups="name", filter={"hostid": hostid})
            result = []
            for i in response[0]['groups']:
                result.append(i['groupid'])
            return result

    def id_to_hostgroupname(self, groupid):
        '''
        根据id获取主机组名称
        '''
        with self._login() as zabbix_api:
            response = zabbix_api.hostgroup.get(filter={"groupid": groupid, "output": "extend"})
            return response[0]['name']

    def id_to_hostname(self, hostid):
        '''
        根据id获取主机名称
        '''
        with self._login() as zabbix_api:
            response = zabbix_api.host.get(filter={"hostid": hostid, "output": "extend"})
            return response[0]['name']

    def get_hostgroupid(self, group_name):
        '''
        获取主机组ID
        :return:
        '''
        with self._login() as zabbix_api:
            response = zabbix_api.hostgroup.get(filter={"name": group_name, "output": "groupid"})
            if not response:
                create_response = self.create_hostgroup(group_name)
                return create_response
            return response[0]['groupid']

    def get_hostid(self, hostname):
        '''
        获取主机ID
        '''
        with self._login() as zabbix_api:
            response = zabbix_api.host.get(filter={"name": hostname, "output": "hostid"})
        return response[0]['hostid']

    def create_hostgroup(self, groupname):
        '''
        创建主机组
        '''
        with self._login() as zabbix_api:
            response = zabbix_api.hostgroup.create(name=groupname)
        return response

    def create_host(self, host_ip, host_name, host_group, zbx_version='5', host_os='linux', active='no', ):
        '''
        创建主机
        :param zbx_version:
        :param host_ip:
        :param host_name:
        :param host_group:
        :param host_os:
        :return:
        '''

        interface = [{
            "type": 1,
            "main": 1,
            "useip": 1,
            "ip": "{}".format(host_ip),
            "dns": "",
            "port": "10050"}]
        groups_list = self.handle_group_list_to_dict(host_group)
        tpl_list = self.judge_tpl_for_zbx_version(host_os, active, zbx_version)
        tpls_id_list = self.handle_tpl_list_to_dict(tpl_list)

        with self._login() as zabbix_api:
            try:
                response = zabbix_api.host.create(
                    interfaces=interface,
                    host=host_name,
                    groups=groups_list,
                    templates=tpls_id_list
                )
                return response
            except Exception as e:
                logger.error(e)

    ################################ Host/Hostgroup Function ##################################

    ################################ Template Function ##################################

    def get_templateid(self, tpl_name):
        '''
        获取模板ID
        :return:
        '''

        with  self._login() as zabbix_api:
            response = zabbix_api.template.get(filter={"host": tpl_name})
            return response[0]['templateid']

    ################################ Template Function ##################################

    ################################ Other Function ##################################
    def judge_tpl_for_zbx_version(self, host_os, active, zbx_version):
        tpl_name_list = []
        if zbx_version == '4':
            # 初始化模板列表
            if host_os == 'linux' and active == 'no':
                tpl_name_list = ['Template OS Linux']
            elif host_os == 'linux' and active == 'yes':
                tpl_name_list = ['Template OS Linux Active']
            elif host_os == 'windows':
                tpl_name_list = ['Template OS Windows']
        elif zbx_version == '5':
            # 初始化模板列表
            if host_os == 'linux' and active == 'no':
                tpl_name_list = ['Template OS Linux by Zabbix agent']
            elif host_os == 'linux' and active == 'yes':
                tpl_name_list = ['Template OS Linux by Zabbix agent active']
            elif host_os == 'windows' and active == 'no':
                tpl_name_list = ['Template OS Windows by Zabbix agent']
            elif host_os == 'windows' and active == 'yes':
                tpl_name_list = ['Template OS Windows by Zabbix agent active']
        return tpl_name_list

    def handle_group_list_to_dict(self, host_group):
        group_id_list = []
        groups_list = []
        group_name_list = host_group.split('/')
        for group_name in group_name_list:
            group_id_list.append(self.get_hostgroupid(group_name))
        for group_id in group_id_list:
            groups_list.append({"groupid": "{}".format(group_id)})
        return groups_list

    def handle_tpl_list_to_dict(self, tpl_name_list):
        tpl_id_list = []
        tpls_list = []
        for tpl_name in tpl_name_list:
            tpl_id_list.append(self.get_templateid(tpl_name))
        for tpl_id in tpl_id_list:
            tpls_list.append({"templateid": "{}".format(tpl_id)})
        return tpls_list

    ################################ Other Function ##################################
